package com.bite.gateway.Filter;


import cn.hutool.json.JSONUtil;
import Constants.JwtConstants;
import Utils.JwtUtil;
import com.bite.common.security.domain.LoginUser;
import domain.R;
import enums.ResultCode;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
@Slf4j
public class MyFilter implements Filter{

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //先获取url路径
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String url = request.getRequestURI();

        //判断是否是登录路径
        if (url.contains("login")){
            //存在的话，直接放行操作
            filterChain.doFilter(request,response);
        }

        //再从请求头中获取token
        String token = request.getHeader(JwtConstants.TOKEN);

        //如果token为空或者不存在，直接给前端显示报错信息
        if (token == null || token.isBlank() || token.isEmpty()){
            R<Object> failed = R.failed(ResultCode.FAILED_UNAUTHORIZED);
            String jsonStr = JSONUtil.toJsonStr(failed);
            response.getWriter().write(jsonStr);
            return;
        }

        Claims claims;
        //成功获取到token之后，进行解析
        try {
            claims  = JwtUtil.parseJWT(token, secret);
        }catch (Exception e){
            R<Object> failed = R.failed(ResultCode.FAILED_UNAUTHORIZED);
            String jsonStr = JSONUtil.toJsonStr(failed);
            response.getWriter().write(jsonStr);
            return;
        }

        //判断claims是否为空
        if (claims == null){
            R<Object> failed = R.failed(ResultCode.FAILED_UNAUTHORIZED);
            String jsonStr = JSONUtil.toJsonStr(failed);
            response.getWriter().write(jsonStr);
            return;
        }

        //先获取到用户ID
        String userId = claims.get(JwtConstants.USER_ID).toString();
        log.info("用户ID为userId:{}",userId);

        //再获取用户信息
        String userKey = claims.get(JwtConstants.USER_KEY).toString();
        log.info("用户信息为userKey:{}",userKey);

        //通过用户信息uerKey来查询redis中的用户信息
        String loginUserStr = redisTemplate.opsForValue().get(userKey);
        LoginUser loginUser = JSONUtil.toBean(loginUserStr, LoginUser.class);
        log.info("用户信息为loginUser:{}",loginUser);

        //最终可以放行了
        filterChain.doFilter(request,response);

    }
}
